//
//  HMHomeTableViewController.swift
//  sinaweibo
//
//  Created by WGP on 16/4/8.
//  Copyright © 2016年 WGP. All rights reserved.
//

import UIKit
import SVProgressHUD
import SVPullToRefresh

private let ReuseIndentifier = "ReuseIndentifier"

class HMHomeTableViewController: HMBaseTabBarViewController {
    
    
/// 微博模型
    var statuses: [HMStatus]?
    {
        didSet
        {
              self.tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !HMUserAccountViewModel.sharedInstance.userLogin
        {
            return
        }

        setupNavgationBar()
        
//        tableView的一些准备工作
        prepareTableView()
        
    }
    
    private func prepareTableView()
    {
        //        注册cell
        tableView.registerClass(HMStatusCell.self, forCellReuseIdentifier: ReuseIndentifier)
        
        
        //        1.设置cell的高度自动填充
        tableView.rowHeight = UITableViewAutomaticDimension
        //        2.设置高度的预估值
//        tableView.estimatedRowHeight = 20
        
        tableView.separatorStyle = .None
        
        
        tableView.addSubview(pullDownRefreshControl)
        pullDownRefreshControl.pullDownRefreshHandle =
        {
            ()->() in
            
            self.loadNewSattus()
        }
        
        pullDownRefreshControl.startRefreshing()
        
        

    }
    
    private func loadMoreOldStatus()
    {
        let max_id = self.statuses?.last?.id ?? 0
        
//        一条微博都没有,就不去加载跟多的数据
        if max_id == 0
        {
            return
        }
        
        HMStatusViewModel.sharedInstance.loadStatus(0, max_id: max_id) { (statuses, error) -> () in
//            让刷新空间结束刷新
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil
            {
                HMPrint("加载更多数据失败:\(error)")
                
                return
            }
            
            let count = statuses?.count ?? 0
            
            if count == 0
            {
                SVProgressHUD.showErrorWithStatus("没有更多数据了")
                return
            }
            
            let s = self.statuses! + statuses!
            self.statuses = s
        }
    }
    
    
    private func loadNewSattus()
    {
        let since_id = self.statuses?.first?.id ?? 0
        
        HMStatusViewModel.sharedInstance.loadStatus(since_id, max_id: 0) { (statuses, error) -> () in
            
            self.pullDownRefreshControl.endRefreshing()
            if error != nil
            {
                SVProgressHUD.showErrorWithStatus("您的网络不给力!")
                return
            }
            
            let count = statuses?.count ?? 0
            
//            在这里能拿到微博的数量
            if since_id != 0
            {
                self.showTipLabel(count)
            }
            
            if count == 0
            {
//                只在第一次没有家在到数据的时候显示,后面的有label可以显示
                if since_id == 0
                {
                    SVProgressHUD.showErrorWithStatus("没有加载到微博数据")
                }
               return
            }
            
            if since_id == 0
            {
                self.statuses = statuses
                //        MARK: - 上拉加载更多
                self.tableView.addInfiniteScrollingWithActionHandler { () -> Void in
                    //            加载更多老数据
                    self.loadMoreOldStatus()
                }
                
            }else
            {
                let arr = statuses! + self.statuses!
                self.statuses = arr
            }
            
        }
    }
    
    private func showTipLabel(count: Int)
    {
        let y = -(UIApplication.sharedApplication().statusBarFrame.height + TipLabelHeight)
        let width = UIScreen.mainScreen().bounds.width
        
        tipLabel.frame = CGRect(x: 0, y: y, width: width, height: TipLabelHeight)
        
        tipLabel.text = count == 0 ? "没有新的微博数据" : "下拉刷新了\(count)条微博数据"
        
//        防止动画叠加
        if let _ = tipLabel.layer.animationKeys()
        {
//            正在执行动画,不要执行后面的动画,但是label的内容更新了
            return
        }
        
//        label动画
       UIView.animateWithDuration(1, animations: { () -> Void in
        
        self.tipLabel.frame = CGRectMake(0, TipLabelHeight, UIScreen.mainScreen().bounds.size.width, TipLabelHeight)
        
        }) { (_) -> Void in
//            停一会,再动画到屏幕上
            UIView.animateWithDuration(1, delay: 0.5, options: [], animations: { () -> Void in
                
                self.tipLabel.frame = CGRect(x: 0, y: y, width: width, height: TipLabelHeight)
                
                }, completion: { (_) -> Void in
                    
//                    控制器一直存在一个label,动画完成不移除,只在屏幕外面,用户看不到
            })
        }
        
    }
    
    

//    MARK: - 添加导航条按钮的私有方法
    private func setupNavgationBar()
    {
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: "didClickPerson")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "didClickQRCode")
        
        
        let name = HMUserAccountViewModel.sharedInstance.userAccount?.screen_name ?? "没有昵称"
        
        
        let titleBtn = HMHomeTitleButton(title: name)
        navigationItem.titleView = titleBtn
        titleBtn.addTarget(self, action: "titleBtnDidClick:", forControlEvents: .TouchDown)
    }
    
//    MARK: - 按钮事件
    @objc private func didClickPerson()
    {
        HMPrint("点击了好友搜素")
    }
    
    @objc private func didClickQRCode()
    {
        HMPrint("点击了二维码扫描")
    }
    
    @objc private func titleBtnDidClick(titleBtn: HMHomeTitleButton)
    {
        titleBtn.selected =  !titleBtn.selected
        UIView.animateWithDuration(HMDefaultAnimationDuration) { () -> Void in
             titleBtn.imageView?.transform = titleBtn.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI)-0.01) : CGAffineTransformIdentity
        }
    }
    
//    选中的时候不高亮
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        
        return false
        
    }
    
// MARK: - 懒加载
    private lazy var pullDownRefreshControl: HMPullDownRefresh = HMPullDownRefresh()
    
    private lazy var tipLabel: UILabel =
    {
        let label = UILabel(fontSize: 14, textColor: UIColor.whiteColor())
        
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = .Center
        
//        只需要添加一次
       self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
    
      return label
        
    }()

}

extension HMHomeTableViewController
{
    // MARK: - Table view data source
    
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIndentifier, forIndexPath: indexPath) as! HMStatusCell
        
        cell.status = statuses?[indexPath.row]
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
//        获取模型
        let status = self.statuses![indexPath.row]
        
//        判断模型里面之前有没有缓存过行高
        if status.rowHeight != nil
        {
//            之前保存过行高,直接返回行高
            return status.rowHeight!
        }
        
//        自己计算行高:AutoLayout自动约束
//        让cell设置对应内容,可以直接直接获取,这个cell不参与显示
        
        let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIndentifier) as! HMStatusCell
        
        cell.status = status
        
        let height = cell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
        
        status.rowHeight = height
        
//        HMPrint("dequeueReusableCellWithIdentifier---\(indexPath.row)")
        
        return height
    }
    
}










